package base2dev.core.model.imp;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import base2dev.core.common.dal.Query;
import base2dev.core.model.Bag;

public class EntityCollection<T extends EntityBase> implements Bag<T> {

	private Query<T> query;

	public void setQuery(Query<T> query) {
		this.query = query;
	}

	protected Query<T> getQuery() {
		return query;
	}

	private SessionFactory sf;

	protected SessionFactory getSessionFactory() {
		return sf;
	}

	public void setSessionFactory(SessionFactory sf) {
		this.sf = sf;
	}

	protected Session getSession() {
		// presumes a current session, which we have through the
		// OpenSessionInViewFilter; doesn't work without that
		return sf.getCurrentSession();
	}

	private Class<T> clazz;

	public Class<T> getClazz() {
		return clazz;
	}

	public void setClazz(Class<T> clazz) {
		this.clazz = clazz;
	}

	public T get(long id) {
		return (T) getSession().get(clazz, id);
	}

	public List<T> getAll() {
		return getSession().createQuery(getQuery().select(clazz).get()).list();
	}

	public Bag<T> remove(T entity) {
		getSession().delete(entity);
		return this;

	}

	public Bag<T> add(T entity) {
		if (entity.getId() == null)
			getSession().save(entity);
		else
			getSession().update(entity);

		return this;
	}

	public Iterator<T> iterator() {
		return getSession().createQuery(getQuery().get()).list().listIterator();
	}

	public Bag<T> byDescription(String desc) {
		getQuery().where("Description like '%1$s'", desc);
		return this;
	}

}
